package com.yzpass.api.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yzpass.api.common.cache.ICache;
import com.yzpass.api.user.dto.ResDTO;
import com.yzpass.api.user.entity.RoleRes;
import com.yzpass.api.user.entity.UserRole;
import com.yzpass.api.user.mapper.RoleResMapper;
import com.yzpass.api.user.mapper.UserRoleMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户权限封装
 */
@Service
public class UserPermissionService {

    @Resource
    UserRoleMapper userRoleMapper;

    @Resource
    RoleResMapper roleResMapper;

    @Resource
    ICache iCache;

    public List<UUID> readRoles(UUID userId){
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,userId);
        List<UserRole> list = userRoleMapper.selectList(wrapper);
        if(list==null){
            return new ArrayList<>();
        }
        return list.stream().map(UserRole::getRoleId).toList();
    }

    public List<ResDTO> readResByRoleId(UUID roleId){
        LambdaQueryWrapper<RoleRes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleRes::getRoleId,roleId);
        List<RoleRes> list = roleResMapper.selectList(queryWrapper);
        if(list!=null){
           return  list.stream().map(ResDTO::from).toList();
        }
        return new ArrayList<>();
    }

    public Set<String> getPemissionSet(UUID userId){
        String userRoleKey = userRoleKey(userId);
        List<UUID> roleIds = iCache.getAndCache(userRoleKey,this::readRoles,userId);
        Set<String> set = new HashSet<>();
        for(UUID uuid:roleIds){
            String roleResKey = roleResKey(uuid);
            List<ResDTO> resDTOS = iCache.getAndCache(roleResKey,this::readResByRoleId,uuid);
            for(var dto: resDTOS){
                set.add(dto.getResId() + ":" + PermissionLevel.READ.getTitle());
                if(Boolean.TRUE.equals(dto.getEdit())){
                    set.add(dto.getResId() + ":" + PermissionLevel.EDIT.getTitle());
                }
                if(Boolean.TRUE.equals(dto.getFullControl())){
                    set.add(dto.getResId()+ ":" + PermissionLevel.FULLCONTROL.getTitle());
                }
            }
        }
        return  set;
    }
    public String roleResKey(UUID roleId){
        return "role:res:" + roleId.toString();
    }
    public String userRoleKey(UUID userId){
        return "user:role:" + userId.toString();
    }

}
